﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Text.RegularExpressions;
namespace ShahyadS.TFSBuildInspectionModel
{
	public static class BuildExtensions
	{
		private static Dictionary<Uri,BuildCustomInfo> customInfos = new Dictionary<Uri,BuildCustomInfo>();
		public static BuildCustomInfo GetBuildCustomInfo(this IBuildDetail bd)
		{
			if (customInfos.ContainsKey(bd.Uri))
			{
				return customInfos[bd.Uri];
			}
			BuildCustomInfo buildCustomInfo = new BuildCustomInfo();
			foreach (var node in bd.Information.Nodes)
			{
				if (node.Fields.ContainsKey("Name"))
				{
					string name = node.Fields["Name"];
					if (name != null && name.Equals("BuildAncestorInfo"))
					{
						string msg = node.Fields["Message"];
						string[] msgtokens = msg.Split(':');
						if (msgtokens.Length > 1)
							buildCustomInfo.BuildAncestorInfo = msgtokens[1];
					}
					if (name != null && name.Equals("TotalNumberOfWarnings"))
					{
						string msg = node.Fields["Message"];
						string[] msgtokens = msg.Split(':');
						if (msgtokens.Length > 1)
							buildCustomInfo.NumberOfWarnings = Int32.Parse(msgtokens[1]);
					}
				}
			}
			customInfos.Add(bd.Uri, buildCustomInfo);
			return buildCustomInfo;
		}
		public static IBuildDetail GetLatestBuild(this IBuildDefinition buildDefinition)
		{
			try
			{
				var bd = buildDefinition.BuildServer.GetBuild(buildDefinition.LastBuildUri);//high speed non accurate
				if (bd != null) 
				{
					return bd;
				}
				throw new Exception();
			}
			catch (Exception)
			{
				var bdspec = buildDefinition.BuildServer.CreateBuildDetailSpec(buildDefinition);
				var bds = buildDefinition.BuildServer.QueryBuilds(bdspec);
				var bd = (from b in bds.Builds select b).OrderBy(b => b.StartTime).LastOrDefault(); //low speed accurate
				if (bd != null)
				{
					return bd;
				}
			}
			return null;
		}
		public static IBuildDetail GetLatestGoodBuild(this IBuildDefinition buildDefinition)
		{
			try
			{
				var bd = buildDefinition.BuildServer.GetBuild(buildDefinition.LastGoodBuildUri);//high speed non accurate
				if (bd != null && bd.Status == BuildStatus.Succeeded) // partially succeeded builds are known as GoodBuild!!!!
				{
					return bd;
				}
				throw new Exception();
			}
			catch (Exception)
			{
				var bdspec = buildDefinition.BuildServer.CreateBuildDetailSpec(buildDefinition);
				bdspec.Status = BuildStatus.Succeeded;
				var bds = buildDefinition.BuildServer.QueryBuilds(bdspec);
				var bd = (from b in bds.Builds where (b.Status == BuildStatus.Succeeded) select b).OrderBy(b => b.StartTime).LastOrDefault(); //low speed accurate
				if (bd != null)
				{
					return bd;
				}
			}
			return null;
		}
	}
}
